package org.eiahe.hr.attendance.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eiahe.hr.attendance.domain.AttendanceRecord;
import org.eiahe.hr.attendance.event.LeaveApprovalEvent;
import org.eiahe.hr.attendance.mapper.AttendanceRecordMapper;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * 请假审批事件监听器
 * 监听请假审批通过事件,批量更新考勤记录状态
 *
 * @author zhangnn
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class LeaveApprovalEventListener {

    private final AttendanceRecordMapper attendanceRecordMapper;

    /**
     * 处理请假审批通过事件
     * 批量更新请假期间的考勤记录状态为"请假"
     */
    @Async
    @EventListener
    @Transactional(rollbackFor = Exception.class)
    public void handleLeaveApprovalEvent(LeaveApprovalEvent event) {
        log.info("收到请假审批事件: 申请ID={}, 工号={}, 审批状态={}",
                event.getApplicationId(), event.getEmployeeNo(), event.getApprovalStatus());

        // 只处理审批通过的情况
        if (!"3".equals(event.getApprovalStatus())) {
            log.debug("审批状态不是通过,跳过处理");
            return;
        }

        try {
            // 计算请假日期范围
            LocalDate startDate = event.getStartTime().toLocalDate();
            LocalDate endDate = event.getEndTime().toLocalDate();

            // 查询请假期间的考勤记录
            LambdaQueryWrapper<AttendanceRecord> lqw = Wrappers.lambdaQuery();
            lqw.eq(AttendanceRecord::getEmployeeNo, event.getEmployeeNo());
            lqw.between(AttendanceRecord::getAttendanceDate, startDate, endDate);
            lqw.in(AttendanceRecord::getAttendanceStatus, "0", "1", "2", "3"); // 正常、迟到、早退、旷工

            List<AttendanceRecord> records = attendanceRecordMapper.selectList(lqw);

            if (records.isEmpty()) {
                log.info("请假期间无考勤记录需要更新");
                return;
            }

            // 批量更新考勤状态为"请假"
            int updatedCount = 0;
            for (AttendanceRecord record : records) {
                record.setAttendanceStatus("4"); // 请假
                record.setExceptionReason("请假申请已通过");
                attendanceRecordMapper.updateById(record);
                updatedCount++;
            }

            log.info("成功更新考勤记录状态: 申请ID={}, 更新记录数={}", event.getApplicationId(), updatedCount);

        } catch (Exception e) {
            log.error("处理请假审批事件失败: 申请ID={}", event.getApplicationId(), e);
            throw e;
        }
    }
}
